import Request from '@/support/request'
import { ref, watch } from 'vue'
import Message from '@/support/message'

export function useExcelDownload() {
  const http = new Request()
  const isSuccess = ref(false)
  const loading = ref<boolean>(false)
  const afterDownload = ref()
  function download(path: string, data: object = {}) {
    loading.value = true
    http
      .setResponseType('blob')
      .init()
      .get(path + '/export', data)
      .then(r => {
          // 生成当前日期字符串
        const date = new Date();
        // const formattedDate = now.toISOString().split('T')[0]; // YYYY-MM-DD 格式
        const year = date.getFullYear()
        const month = date.getMonth()+1
        const nowday = date.getDate()
        
        const hour = date.getHours()
        const minutes= date.getMinutes()
        const seconds = date.getSeconds()
        
        const formattedDate  = `${year}-${padZero(month)}-${padZero(nowday)} ${padZero(hour)}:${padZero(minutes)}:${padZero(seconds)}`

        const filename = `导出订单${formattedDate}.xls`; // 可以根据实际需要修改扩展名
        if (r.headers['content-type'] === 'application/json') {
          const blob = new Blob([r.data], { type: r.headers['content-type'] })
          const blobReader = new Response(blob).json()
          blobReader.then(res => {
            if (res.code === 1e4) {
              Message.success(res.message)
            } else {
              Message.error(res.message)
            }
          })
        } else {
          const downloadLink = document.createElement('a')
          const blob = new Blob([r.data], { type: r.headers['content-type'] })
          downloadLink.href = URL.createObjectURL(blob)
          // downloadLink.download = r.headers.filename
          downloadLink.download = filename
          document.body.appendChild(downloadLink)
          downloadLink.click()
          document.body.removeChild(downloadLink)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }
  const padZero = (value) =>{
    return value<10?`0${value}`:value
  }

  const success = (func: Function) => {
    watch(isSuccess, function () {
      isSuccess.value = false
      func()
    })
  }

  return { download, success, loading, afterDownload }
}
